<script setup lang="ts">
import logo from '@/assets/logo.png'
import logo2 from '@/assets/logo2.png'
import { onMounted, ref, onBeforeUnmount } from 'vue'
import { QueryInfo, RunMonitor, StartMonitor, StopMonitor } from './api/index'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'

import DeviceStatus from './views/components/DeviceStatus.vue'
import ParameterSetting from './views/components/ParameterSetting.vue'
import DataSearch from './views/components/DataSearch.vue'
const activeName = ref('first')

const runStatus = ref('pending')
//总启动开关
const linkRun = ref(false)
const loading = ref(false)

// const beforeChange = () => {
//   loading.value = true
//   if (linkRun.value) {
//     const post = {
//       InputStr: 'OperType=StopMonitor',
//       JsonStr: []
//     }
//     return new Promise((resolve: any) => {
//       StopMonitor(post).then((res: any) => {
//         if (res.code == 200) {
//           loading.value = false
//           ElMessage.success(res.msg)
//           return resolve(true)
//         }
//         ElMessage.warning(res.msg)
//       })
//     })
//   } else {
//     const post = {
//       InputStr: 'OperType=StartMonitor',
//       JsonStr: []
//     }
//     return new Promise((resolve: any) => {
//       StartMonitor(post).then((res: any) => {
//         if (res.code == 200) {
//           loading.value = false
//           ElMessage.success(res.msg)
//           return resolve(true)
//         }
//         ElMessage.warning(res.msg)
//       })
//     })
//   }
// }
// const handleChange = () => {
//   //修改状态文本
//   runStatus.value = linkRun.value ? 'running' : 'pending'
// }

//开启后台
const runMonitor = () => {
  const post = {
    InputStr: 'OperType=RunMonitor',
    JsonStr: []
  }
  RunMonitor(post).then((res: any) => {
    if (res.code == 200) {
      console.log(`RunMonitor->success`)
    }
  })
}
//关闭后台
const stopMonitor = () => {
  const post = {
    InputStr: 'OperType=StopMonitor',
    JsonStr: []
  }
  StopMonitor(post).then((res: any) => {
    if (res.code == 200) {
      console.log(`StopMonitor->success`)
    }
  })
}

//故障统计
const faultData = ref([])
//警报信息
const alarmData = ref({
  WarningQty: 0,
  AlarmQty: 0
})
//状态统计
const statusData = ref([])
//开启运行 获取状态
const getState = () => {
  const post = {
    InputStr: 'OperType=GetFeederState',
    JsonStr: []
  }
  QueryInfo(post).then((res: any) => {
    if (res.code === 200) {
      const { SSTInfo, StatusInfo, ErrInfo } = res.data
      statusData.value = SSTInfo
      feederData.value = StatusInfo
      faultData.value = ErrInfo
    }
  })
}

//获取基本信息
interface System {
  SystemName: string
  CustName: string
  Factory: string
  Floor: string
  Line: string
  Version: string
}
//系统信息
const systemData = ref<System>({
  SystemName: '',
  CustName: '',
  Factory: '',
  Floor: '',
  Line: '',
  Version: ''
})

//班别
const shift = ref('D')

//启动按钮是否开启
// const runAvailable = ref(false)
const mailData = ref({})
//收料信息
const feederData = ref([])
//获取基本信息
const getInfo = () => {
  const post = {
    InputStr: 'OperType=GetInitInfo',
    JsonStr: []
  }
  QueryInfo(post).then((res: any) => {
    if (res.code === 200) {
      const { SystemInfo, MailInfo, FeederInfo, ErrInfo, RunInfo } = res.data
      // runAvailable.value = RunInfo[0].OpenStatus == 'true' ? true : false
      //修改状态文本
      //修改状态文本
      const runTemp = RunInfo[0].RunStatus
      runStatus.value = runTemp == 'true' ? 'running' : 'pending'
      //openStatus为true 说明是本人操作，如果linkRun为开启则开启RunMonitor定时循环1秒 否则关闭定时
      systemData.value = JSON.parse(JSON.stringify(SystemInfo[0]))
      mailData.value = JSON.parse(JSON.stringify(MailInfo[0]))
      feederData.value = JSON.parse(JSON.stringify(FeederInfo))
      faultData.value = JSON.parse(JSON.stringify(ErrInfo))
      //格式化邮件
      const { FilePath } = mailData.value
      //将路径中的:\替换为:/
      const newPath = FilePath.replace(/\$/g, '\\')
      mailData.value.FilePath = newPath
    }
  })
}

const updateSystem = (data: any) => {
  systemData.value = data
}

//刷新周期
const cycle = ref(5 * 1000)
const timerList = ref<any[]>([])
const clearAllTimer = () => {
  // 清除所有的定时器
  for (let i = 0; i < timerList.value.length; i++) {
    clearTimeout(timerList.value[i])
  }
  // 清除列表
  timerList.value = []
  console.log('clearAllTimerList', timerList.value)
}

/**
 * 固定轮询5秒 loop
 */
const lineLoopTimer = ref()
//异步请求拿到结果 停止轮询
const syncPromiseLine = () => {
  faultData.value = []
  const post = {
    InputStr: 'OperType=GetFeederState',
    JsonStr: []
  }
  return new Promise((resolve) => {
    QueryInfo(post)
      .then((res: any) => {
        if (res.code == 200) {
          const { SSTInfo, StatusInfo, ErrInfo, ErrAlarmInfo, RunInfo } = res.data
          statusData.value = SSTInfo
          feederData.value = StatusInfo
          faultData.value = ErrInfo.map((item: any) => {
            return {
              ...item,
              Qty: parseInt(item.Qty)
            }
          })
          const { WarningQty, AlarmQty } = ErrAlarmInfo[0]
          alarmData.value = {
            WarningQty: parseInt(WarningQty),
            AlarmQty: parseInt(AlarmQty)
          }
          shift.value = RunInfo[0].Shift

          //如果检查到返回值为Y则要重新启动RunMonitor
          // if (RunInfo[0].ReStart == 'true') {
          //   runMonitor()
          // }
          //修改状态文本
          runStatus.value = RunInfo[0].RunStatus == 'true' ? 'running' : 'pending'
          // //按钮置灰时 表明是只读权限 需要根据接口返回的值去修改开关状态
          // if (!runAvailable.value) {
          //   // linkRun.value = RunInfo[0].RunStatus == 'true' ? true : false
          //   //修改状态文本
          //   runStatus.value = RunInfo[0].RunStatus == 'true' ? 'running' : 'pending'
          // }
        }
        resolve(1)
      })
      .catch((err) => {
        resolve(1)
      })
  })
}
//控制轮询的间隔时间 并在指定时间执行请求
const pollingPrimiseLine = () => {
  return new Promise((resolve) => {
    lineLoopTimer.value = setTimeout(async () => {
      const result = await syncPromiseLine()
      resolve(result)
    }, cycle.value)
    timerList.value.push(lineLoopTimer.value)
  })
}
//轮询入口
const lineFlag = ref(true)
const startPollingLine = async () => {
  clearTimeout(lineLoopTimer.value)
  lineLoopTimer.value = ''
  let needPolling = await syncPromiseLine()
  console.log(`output->needPolling, lineFlag.value`, needPolling, lineFlag.value)
  while (needPolling && lineFlag.value) {
    needPolling = await pollingPrimiseLine()
  }
  console.log('设备状态轮询请求处理完成！')
}
const lineLoop = async () => {
  await startPollingLine()
  console.log('设备状态请求被clearTimeOut 这里不会被执行')
}

//清除Query
const tempTimer = ref()
const clearLineLoop = () => {
  // 当前lineFlag为true且lineLoopTimer true 清除GetLineState定时器
  if (lineFlag.value && lineLoopTimer.value) {
    clearTimeout(lineLoopTimer.value)
    lineLoopTimer.value = ''
    clearAllTimer()
    lineFlag.value = false
    tempTimer.value = setTimeout(() => {
      lineFlag.value = true
      lineLoop()
      clearTimeout(tempTimer.value)
      tempTimer.value = ''
      console.log(`output->clear success`)
    }, 0)
    console.log('clearLineLoopTimer', lineLoopTimer.value)
  }
}

const intervalTime = ref(10 * 60 * 1000)

// 初始化一个变量来保存定时器
let intervalId: any
// 设置定时器函数
function startTimer() {
  // 清除之前可能设置的定时器
  if (intervalId) {
    clearInterval(intervalId)
  }

  // 设置一个新的定时器，每隔10分钟（10 * 60 * 1000 600000毫秒）执行一次指定的函数
  intervalId = setInterval(() => {
    console.log(`LineLoop每隔${intervalTime.value / (60 * 1000)}分钟执行一次`)
    // 代码逻辑
    clearLineLoop()
  }, intervalTime.value)
}
// 如果需要在某个时刻停止定时器，可以调用以下函数
function stopTimer() {
  if (intervalId) {
    clearInterval(intervalId)
    intervalId = null
  }
}

const current = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
let currentTime = ref(current)
let timerID = ref()
onMounted(() => {
  timerID.value = setInterval(() => {
    currentTime.value = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  }, 1000)
  getInfo()
  setTimeout(() => {
    //开启轮询
    lineFlag.value = true
    lineLoop()
    // 调用函数来启动定时器
    startTimer()
  }, 2 * 1000)
})
onBeforeUnmount(() => {
  clearInterval(timerID.value)
  timerID.value = null
})
</script>

<template>
  <div class="overflow-hidden main">
    <div class="header">
      <img class="left-logo" :src="logo" width="170" height="45" />
      <div class="header-title">
        <p>{{ systemData.SystemName || '供料器看板系统' }}</p>
      </div>
      <img class="right-logo" :src="logo2" width="100" height="46" />
    </div>
    <!-- 客户&线别信息 -->
    <div class="cus-info flex items-center justify-between">
      <div class="flex">
        <p class="ml-3 w-96">客户：{{ systemData.CustName }}</p>
        <p class="ml-3 w-80">厂区：{{ systemData.Factory }}</p>
        <p class="ml-3 w-80">楼层：{{ systemData.Floor }}</p>
        <p class="ml-3 w-80">线别：{{ systemData.Line }}</p>
        <p class="ml-7">班别：{{ shift }}</p>
      </div>
      <div class="user-info mr-4">{{ currentTime }}</div>
    </div>
    <section class="flex">
      <div class="content mt-4">
        <el-tabs v-model="activeName">
          <el-tab-pane label="设备状态" name="first">
            <DeviceStatus
              :faultData="faultData"
              :feederData="feederData"
              :statusData="statusData"
              :alarmData="alarmData"
            />
          </el-tab-pane>
          <el-tab-pane label="参数设置" name="second">
            <ParameterSetting
              :systemData="systemData"
              :mailData="mailData"
              @updateSystem="updateSystem"
            />
          </el-tab-pane>
          <!-- <el-tab-pane label="设备参数" name="third">设备参数</el-tab-pane> -->
          <el-tab-pane label="数据查询" name="fourth">
            <DataSearch />
          </el-tab-pane>
        </el-tabs>
        <div class="run-status flex">
          <div class="flex items-center">
            <div>
              <span v-if="runStatus === 'running'" class="text-green-500" type="success"
                >运行中</span
              >
              <span v-if="runStatus === 'pending'" class="text-amber-500" type="warning"
                >待启动</span
              >
            </div>
            <!-- <el-switch
              v-model="linkRun"
              size="large"
              :loading="loading"
              :disabled="!runAvailable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              :before-change="beforeChange"
              @change="handleChange"
            /> -->
          </div>
          <!-- <div class="mr-1">版本：{{ systemData.Version }}</div> -->
        </div>
      </div>
    </section>
  </div>
</template>
<style lang="less">
.main {
  background: #0d0f20;
  color: #fff;
  font-size: 1.5rem;
}

.header {
  position: relative;
  height: 80px;
  color: #fff;
  line-height: 80px;
  text-align: center;

  .left-logo {
    position: absolute;
    object-fit: contain;
    top: 5px;
    left: 10px;
    height: 45px;
    align-items: center;
  }

  .right-logo {
    position: absolute;
    top: 2px;
    right: 10px;
    object-fit: contain;
  }

  .header-title {
    background: url(./assets/header-bg.png) no-repeat center center;
    p {
      font-weight: 400;
      font-size: 30px;
      color: #ffffff;
      line-height: 62px;
    }
  }
}

.cus-info {
  p {
    width: 231px;
    height: 42px;
    background: url(./assets/cus-info-bg.png) no-repeat center center;
    text-align: center;
    line-height: 42px;
    font-size: 20px;
  }
  .user-info {
    margin-right: 15px;
  }
}

.content {
  position: relative;
  width: 100%;
  height: calc(100vh - 90px);
  overflow: hidden;
  padding: 0 15px;
}

.el-tabs__item {
  width: 147px !important;
  height: 32px !important;
  background: url(./assets/tab-bg.png) no-repeat center center;
  color: #fff !important;
  font-size: 18px !important;
  padding: 0 !important;
}
.el-tabs__item.is-active {
  background: url(./assets/tab-bg-actived.png) no-repeat center center;
  color: var(--el-color-primary) !important;
}

.el-tabs__nav-wrap::after {
  display: none !important;
}
.el-tabs__active-bar {
  display: none !important;
}
.run-status {
  position: absolute;
  right: 15px;
  top: -5px;
  height: 50px;
  .el-switch {
    transform: scale(1.4);
    margin-left: 14px;
  }
}
</style>
